package com.hb.guli.service.vod.controller.admin;

import com.aliyuncs.exceptions.ClientException;
import com.hb.guli.common.base.result.R;
import com.hb.guli.common.base.result.ResultCodeEnum;
import com.hb.guli.common.base.util.ExceptionUtils;
import com.hb.guli.service.base.exception.GuliException;
import com.hb.guli.service.vod.service.VideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Api("阿里云视频管理")
@CrossOrigin
@RestController
@RequestMapping("/admin/vod/media")
@Slf4j
public class MediaController {

    @Autowired
    private VideoService videoService;

    // videoId 指视频 id

    @ApiOperation("视频上传")
    @PostMapping("upload")
    public R uploadVideo(@ApiParam(name = "文件", value = "文件", required = true)
                         @RequestParam("file") MultipartFile file) {
        try {
            final InputStream inputStream = file.getInputStream();
            final String originalFilename = file.getOriginalFilename();
            final String videoId = videoService.upload(inputStream, originalFilename);
            return R.ok().message("上传成功").data("videoId", videoId);
        } catch (IOException e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_TOMCAT_ERROR);
        }
    }

    @ApiOperation("视频删除")
    @DeleteMapping("remove/{videoId}")
    public R removeVideo(@ApiParam(name = "videoId", value = "阿里云视频id", required = true)
                         @PathVariable String videoId) {
        try {
            videoService.removeVideo(videoId);
            return R.ok().message("视频删除成功");
        } catch (ClientException e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GuliException(ResultCodeEnum.VIDEO_DELETE_ALIYUN_ERROR);
        }
    }

    @ApiOperation("视频删除")
    @DeleteMapping("remove")
    public R removeVideoByIdList(@ApiParam( value = "阿里云视频id列表", required = true)
                         @RequestBody List<String> removeVideoByIdList) {
        try {
            videoService.removeVideoByIdList(removeVideoByIdList);
            return R.ok().message("视频删除成功");
        } catch (ClientException e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GuliException(ResultCodeEnum.VIDEO_DELETE_ALIYUN_ERROR);
        }
    }
}
